<template>
  <div v-show="visible && length > 0" :style="style">
    <template v-for="(column, key) in searchColumns">
      <template v-if="column.op == 'like'">
        <ElInput v-show="isShow(key)" v-model="data[`search_${key}`]" :placeholder="`请输入${column.label}`" @keyup.enter.stop="search"/>
      </template>
      <template v-else-if="column.op == 'eq'">
        <ElInput v-show="isShow(key)" v-model="data[`search_${key}`]" :placeholder="`请输入${column.label}`" @keyup.enter.stop="search"/>
      </template>
      <template v-else-if="column.op == 'between'">
        <span v-show="isShow(key)">
          <ElInput v-model="data[`search_${key}`]" :placeholder="`请输入起始${column.label}`" @keyup.enter.stop="search" class="w-47%"/>
          <span class="w-6%">到</span>
          <ElInput v-model="data[`search_${key}`]" :placeholder="`请输入结束${column.label}`" @keyup.enter.stop="search" class="w-47%"/>
        </span>
      </template>
      <template v-else>
        <ElInput v-show="isShow(key)" v-model="data[`search_${key}`]" :placeholder="`请输入${column.label}`" @keyup.enter.stop="search"/>
      </template>
    </template>
    <div class="flex">
      <ElButton type="primary" @click="search">搜 索</ElButton>
      <ElButton @click="reset">重 置</ElButton>
      <ElButton v-show="length >= 5" link @click="collapse = !collapse">
        <span class="mr5px">{{ collapse ? '展开' : '折叠' }}</span>
        <Icon v-if="collapse" icon="ep:arrow-down-bold" />
        <Icon v-else icon="ep:arrow-up-bold" />
      </ElButton>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ElButton, ElInput } from 'element-plus'
  import { inject, ref, unref } from 'vue'
  import { getSearchColumns } from '@/seed-application/utils/SeedUtil'; 
  import { Action, Unit } from '@/seed-application/types';
  import { Icon } from '@/components/Icon'
  import { unitKey } from '@/seed-application';

  const props = defineProps<{action: Action}>()
  const unit = inject<Unit>(unitKey, void 0)
  const action = props.action
  
  const searchColumns = getSearchColumns(action)

  const keys = Object.keys(searchColumns)
  const length = keys.length
  const style = {
    display: 'grid',
    gridTemplateColumns: `repeat(${length < 5 ? length + 1 : 5}, minmax(0, 1fr))`,
    gap: '10px 5px'
  }

  const collapse = ref(true)
  const isShow = (key) => {
    if(keys.findIndex(k => k == key) < 4) return true

    return !collapse.value
  }

  const data = ref({})

  const search = () => {
    unit.searchData = { ...data.value }
    unit.refresh?.()
  }
  
  const reset = () => {
    data.value = {}
    unit.searchData = {}
    unit.refresh?.()
  }

  const visible = ref(true)
  const show = () => visible.value = true
  const hide = () => visible.value = false
  const toggle = () => visible.value = !unref(visible)

  defineExpose({ show, hide, toggle, visible, length })
</script>